package com.yellow.cloud.system.controller;

import com.yellow.cloud.system.service.CaptchaService;
import com.yellowframework.cloud.api.system.CaptchaControllerApi;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/captcha")
public class CaptchaController implements CaptchaControllerApi {

    @Resource
    private CaptchaService captchaService;

    /**
     * 验证码
     */
    @GetMapping("{uuid}.jpg")
    public void captcha(HttpServletResponse response, @PathVariable("uuid") String uuid) throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        //获取图片验证码
        BufferedImage image = captchaService.getCaptcha(uuid);

        try(ServletOutputStream out = response.getOutputStream()){
            ImageIO.write(image, "jpg", out);
            out.flush();
        }
    }
}
